
#ifndef EVENTMONITOR_H
#define EVENTMONITOR_H

#include <QThread>
#include <X11/Xlib.h>
#include <X11/extensions/record.h>
#include <QKeySequence>
#include <QMap>

//sudo apt install libxtst-dev
// Virtual button codes that are not defined by X11.
#define Button1			1
#define Button2			2
#define Button3			3
#define WheelUp			4
#define WheelDown		5
#define WheelLeft		6
#define WheelRight		7
#define XButton1		8
#define XButton2		9

class KeyEventMonitor : public QThread
{
    Q_OBJECT

public:

    static KeyEventMonitor& instance() { static KeyEventMonitor v; return v; }
    void startMonitor();
    void stopMonitor(bool waitExit = false);
    bool setMonitShortcutKeys(const QString& name, const QString& keySequences);
    void setPause(bool pause);
    QString getShortcutKeys(const QString& name);
signals:
    void mousePress(quint8 code, int x, int y);
    void mouseMove(quint8 code, int x, int y);
    void mouseRelease(quint8 code, int x, int y);
    void keyPress(quint8 code);
    void keyRelease(quint8 code);
    void shortcutKeyPress(const QString& name);
protected:
    bool filterWheelEvent(int detail);
    static void callback(XPointer trash, XRecordInterceptData* data);
    void handleRecordEvent(XRecordInterceptData *);
    void run();

private:
    KeyEventMonitor(QObject *parent = nullptr);
    bool m_exiting = false;
    bool m_isPaused = false;
    bool m_useAsync = false;
    QMap<QString, QKeySequence> m_cutKeys;
    Display* m_display_ctrl = nullptr;
    Display* m_display_data = nullptr;
    XRecordContext m_context = 0;
    void checkShortcutKey(KeyCode code);
};

#endif
